package com.itlaoqi.thread;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;
import java.util.concurrent.TimeUnit;

public class SemaphoreSample2 {

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        Semaphore semaphore = new Semaphore(5);//定义5个信号量，也就是说服务器只允许5个人再里面玩
        for (int i = 0; i <= 20; i++) {
            final int index = 1;
            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        if(semaphore.tryAcquire(5, TimeUnit.SECONDS)){//获取一个信号量//占用一个跑道
                            play();
                            semaphore.release();//执行完成后释放这个信号量,"从跑道出去"
                            semaphore.acquire();
                        }else{
                            System.out.println(Thread.currentThread().getName() + "对不起,服务器");
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
        threadPool.shutdown();
    }
    public static void play(){
        System.out.println(new Date() + Thread.currentThread().getName() + "获得紫禁之巅服务器进入资格");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(new Date() + Thread.currentThread().getName() + "紫禁之巅服务器退出");
    }
}
